// Copyright (c) 2013, The mangorippers. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// The golang stdlib is used here and is licensed under the 3-clause New BSD.
// The go-charset library is used here as well and is also licensed under the 3-clause New BSD.

// mangastreamFeeder
// An mangastream.com rss reader that feeds arguments to mangoripper.
// https://code.google.com/p/mangoripper/mangastreamFeeder
package main

import (
	"code.google.com/p/go-charset/charset"
	_ "code.google.com/p/go-charset/data"
	"encoding/xml"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
)

type release struct {
	XMLName xml.Name `xml:"item"`
	Title   string   `xml:"title"`
	Link    string   `xml:"link"`
	PubDate string   `xml:"pubDate"`
}
type channel struct {
	XMLName     xml.Name  `xml:"channel"`
	ReleaseList []release `xml:"item"`
}
type result struct {
	XMLName xml.Name `xml:"rss"`
	Channel channel  `xml:"channel"`
}

func decodeXML(file io.Reader, v interface{}) error {
	decoder := xml.NewDecoder(file)
	decoder.Entity = xml.HTMLEntity
	decoder.CharsetReader = charset.NewReader
	return decoder.Decode(v)
}

func download(url string) io.ReadCloser {
	res, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	if res.StatusCode < 200 || res.StatusCode > 299 {
		log.Fatal("Server returned error status code: ", res.StatusCode)
	}
	return res.Body
}

func main() {
	inMsg := "\nmangastreamFeeder: A mangastream.com rss reader that feeds arguments to mangoripper.\n"
	f := func() *result {
		v := &result{}
		res := download("http://mangastream.com/rss")
		err := decodeXML(res, v)
		if err != nil {
			log.Printf("error: %v", err)
		}
		res.Close()
		return v
	}

	switch len(os.Args) {
	case 1:
		v := f()
		for key, value := range v.Channel.ReleaseList {
			inMsg = inMsg + "[" + strconv.Itoa(key) + "] " + value.Title + " " + value.Link + "\n"
		}
	case 2:
		v := f()
		rls, err := strconv.Atoi(os.Args[1])
		if err != nil {
			log.Printf("error: %v", err)
		}
		for key, value := range v.Channel.ReleaseList {
			if key == rls {
				inMsg = strings.Replace(value.Title, " ", "_", -1)
				inMsg = strings.Replace(inMsg, "'", "", -1)
				inMsg = strings.Replace(inMsg, "\"", "", -1)
				inMsg = inMsg + " " + value.Link
			}
		}
	case 3:
		v := f()
		rls, err := strconv.Atoi(os.Args[1])
		if err != nil {
			log.Printf("error: %v", err)
		}
		for key, value := range v.Channel.ReleaseList {
			if key == rls {
				inMsg = strings.Replace(value.Title, " ", "_", -1) + " " + os.Args[2] + " " + value.Link
			}
		}
	default:
		inMsg = inMsg + "Ha?"
	}

	fmt.Println(inMsg)
}
